package LeetCode.leetcode;

/**
 * 旋转数组
 * @author: leiwenkang02@meituan.com
 * @date: 2019/1/8
 * @time: 19:32
 */
public class Test189旋转数组 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6, 7};
        rotate(nums, 7);
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i]);
            System.out.print(" ");
        }
    }


    public static void rotate(int[] nums, int k) {
        if (nums == null || nums.length == 0 || k <= 0) {
            return;
        }
        //旋转nums.length相当于没有旋转
        k = k % nums.length;
        //将数组分成两部分，先将0到nums.length - k - 1部分的数组反转
        reverse(nums, 0, nums.length - k - 1);
        //再将nums.length - k到nums.length-1部分的数组反转
        reverse(nums, nums.length - k, nums.length - 1);
        //最后将这个数组再次反转
        reverse(nums, 0, nums.length - 1);
    }

    public static void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }



}
